package org.sunriz.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;

import java.util.HashMap;
import java.util.List;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.sunriz.DAO.Signal;
import org.sunriz.utils.Constant;
import org.sunriz.utils.FolderUtil;

public class AllOutputToExcel {
    public static void allOutputToExcel(HashMap<String, List<Signal>> output) {
        // 创建excel    
        String excelName = Constant.ALL_OUTPUT_EXCEL_NAME;

            // 获取文件路径
            Path filePath = FolderUtil.getFilePath();
            String filePathString = filePath.toString() + "\\" + excelName ;
            File file = new File(filePathString);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            // 创建excel文件
            try (OutputStream outputStream = new FileOutputStream(file)) {
                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet("所有的输出点");

                Row row = sheet.createRow(0);
                row.createCell(0).setCellValue("控制器编号");
                row.createCell(1).setCellValue("页码");
                row.createCell(2).setCellValue("块号");
                row.createCell(3).setCellValue("点名");
                row.createCell(4).setCellValue("类型");

                int i = 1;
                
                for (String fileName : output.keySet()) {
                    List<Signal> signals = output.get(fileName);
                    for (Signal signal : signals) {
                        Row row1 = sheet.createRow(i);
                        row1.createCell(0).setCellValue(fileName);
                        row1.createCell(1).setCellValue(signal.getPageNumber());
                        row1.createCell(2).setCellValue(signal.getBlockID());
                        row1.createCell(3).setCellValue(signal.getName());
                        row1.createCell(4).setCellValue(signal.getType());  
                        i++;
                    }
                }

                workbook.write(outputStream);
                outputStream.close();
                System.out.println("✅ 未引用的输入点已生成,文件路径: " + filePathString);

            } catch (IOException e) {
                e.printStackTrace();
            }   

    }
}
